<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 添加分类 -->
      <el-button type="primary" @click="addClass">添加分类</el-button>
      <!-- 带折叠树的表格 -->
      <div class="tree-table">
        <tree-table :data="classInfo.result" :columns="columns" :selection-type="false" :expand-type="false" show-index
          index-text="#" border>

          <template slot="isok" slot-scope="scope">
            <i class="el-icon-success" v-if="scope.row.cat_deleted==false"
              style="color: lightgreen; font-size:24px;"></i>
            <i class="el-icon-error" v-else style="color: red; font-size:24px;"></i>
          </template>

          <template slot="order" slot-scope="scope">
            <el-tag v-if="scope.row.cat_level == '0'">一级</el-tag>
            <el-tag type="success" v-else-if="scope.row.cat_level == '1'">二级</el-tag>
            <el-tag type="info" v-else>三级</el-tag>
          </template>

          <template slot="modify" slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="handleRename(scope.row)">修改
            </el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteClass(scope.row.cat_id)">删除
            </el-button>
          </template>
        </tree-table>
      </div>

      <!-- 分页器 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="pagination.pagenum" :page-sizes="[1, 2, 5, 7]" :page-size="pagination.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="pagination.total">
      </el-pagination>
    </el-card>
    <!-- 添加分类的对话框 -->
    <el-dialog title="添加分类" :visible.sync="addClassVisible" @close="clearDialog">
      <el-form :model="addClassForm" ref="addClassRef" :rules="addClassRule">
        <el-form-item label="分类名称" label-width="80px" prop="cat_name">
          <el-input v-model="addClassForm.cat_name" autocomplete="off"></el-input>
        </el-form-item>
        <!-- 级联选择器 -->
        <el-form-item label="父级名称" label-width="80px">
          <div class="block">
            <el-cascader v-model="selected" :options="classes" :props="cascaderProps" style="width: 100%"
              change-on-select clearable>
            </el-cascader>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addClassVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddClass">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑分类信息的对话框 -->
    <el-dialog title="编辑分类" :visible.sync="editClassVisible" @close="clearEditClass">
      <el-form :model="editClass" ref="editClassFormRef" :rules="editClassRule">
        <el-form-item label="分类名称" label-width="80px" prop="cat_name">
          <el-input v-model="editClass.cat_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="editClassVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditClass">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style lang="less" scoped>
  .el-breadcrumb {
    margin-bottom: 20px;
  }

  .cell {
    text-align: center;
  }

  .tree-table {
    margin-top: 20px;
    margin-bottom: 20px;
  }

</style>


<script>
  export default {
    data() {
      return {
        classInfo: [],
        pagination: {
          pagenum: 1,
          pagesize: 7,
          total: 0
        },
        columns: [{
            label: '分类名称',
            prop: 'cat_name',
          },
          {
            label: '是否有效',
            type: 'template',
            template: 'isok'
          },
          {
            label: '排序',
            type: 'template',
            template: 'order'
          }, {
            label: '操作',
            type: 'template',
            template: 'modify',
            width: 300
          }
        ],
        addClassForm: {
          cat_name: "",
          cat_pid: "0",
          cat_level: "0"
        },
        addClassVisible: false,
        editClassVisible: false,
        cascaderProps: {
          expandTrigger: 'hover',
          value: "cat_id",
          label: "cat_name",
          children: "children"
        },
        selected: [],
        classes: [],
        addClassRule: {
          cat_name: [{
            required: true,
            message: '请输入分类的名称',
            trigger: 'blur'
          }]
        },
        classInfo: {},
        editClassRule: {
          cat_name: [{
            required: true,
            message: '请输入分类的名称',
            trigger: 'blur'
          }]
        },
        editClass: {
          cat_name: '',
          id: 0
        }
      }
    },
    methods: {
      async getClassList() {
        const {
          data: response
        } = await this.$http.get('categories', {
          params: {
            type: 3,
            pagenum: this.pagination.pagenum,
            pagesize: this.pagination.pagesize
          }
        });
        if (response.meta.status == 200) {
          this.classInfo = response.data;
          this.pagination.total = this.classInfo.total;
        } else {
          this.$message.error(response.meta.msg);
        }
      },
      handleSizeChange(size) {
        this.pagination.pagesize = size;
        this.getClassList();
      },
      handleCurrentChange(pagenum) {
        this.pagination.pagenum = pagenum;
        this.getClassList();
      },
      async handleDelete(classInfo) {

      },
      addClass() {
        this.addClassVisible = true;
        this.getClasses();
      },
      clearDialog() {
        this.$refs.addClassRef.resetFields();
        this.selected = [];
      },
      // 获取所有的1，2级分类
      async getClasses() {
        const {
          data: res
        } = await this.$http.get('categories', {
          params: {
            type: 2
          }
        });
        if (res.meta.status == 200) {
          this.classes = res.data;
        } else {
          this.$message.error(res.meta.msg);
        }
      },
      submitAddClass() {
        this.$refs.addClassRef.validate(async (valid) => {
          if (valid) {
            this.addClassVisible = false;
            if (this.selected.length > 0) {
              this.addClassForm.cat_pid = this.selected[this.selected.length - 1];
              this.addClassForm.cat_level = this.selected.length;
            } else {
              this.addClassForm.cat_pid = 0;
              this.addClassForm.cat_level = 0;
            }
            const {
              data: response
            } = await this.$http.post('categories', this.addClassForm);
            if (response.meta.status == 201) {
              this.$message.success(response.meta.msg);
              this.getClassList();
            } else {
              this.$message.error(response.meta.msg);
            }

          }
        });
      },
      handleRename(editClass) {
        this.editClassVisible = true;
        this.editClass = {
          cat_name: editClass.cat_name,
          id: editClass.cat_id
        }
      },
      clearEditClass() {
        this.$refs.editClassFormRef.resetFields();
      },
      submitEditClass() {
        this.$refs.editClassFormRef.validate(async (valid) => {
          if (valid) {
            this.editClassVisible = false;
            const {
              data: response
            } = await this.$http.put(`/categories/${this.editClass.id}`, {
              cat_name: this.editClass.cat_name
            });
            if (response.meta.status == 200) {
              this.$message.success(response.meta.msg);
              this.getClassList();
            } else {
              this.$message.error(response.meta.msg);

            }
          }
        });
      },
      deleteClass(classId) {
        this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'danger'
        }).then(async () => {
          const {
            data: response
          } = await this.$http.delete(`/categories/${classId}`);
          if (response.meta.status == 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.deleteViewData(classId, this.classInfo.result);
          } else {
            this.$message({
              type: 'info',
              message: response.meta.msg
            });
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      deleteViewData(cat_id, array) {
        array.forEach(element => {
          if (element.cat_id == cat_id) {
            array.splice(array.indexOf(element), 1);
            console.log(array);
            console.log(element);
          } else {
            if (element.children) {
              this.deleteViewData(cat_id, element.children);
            }
          }
        });
      }
    },
    created() {
      this.getClassList();
    }
  }

</script>
